package com.mce.nebula.service;

import com.mce.nebula.common.UuidGenerator;
import com.mce.nebula.dto.TeamRoleCreateRequest;
import com.mce.nebula.entity.TeamRole;
import com.mce.nebula.entity.TeamRolePermission;
import com.mce.nebula.repository.TeamRolePermissionRepository;
import com.mce.nebula.repository.TeamRoleRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 团队角色服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeamRoleService {
    
    private final TeamRoleRepository teamRoleRepository;
    private final TeamRolePermissionRepository teamRolePermissionRepository;
    
    /**
     * 创建团队角色
     */
    @Transactional
    public TeamRole createTeamRole(TeamRoleCreateRequest request, String tenantId, String enterpriseId) {
        // 检查角色名是否已存在
        if (teamRoleRepository.existsByTenantIdAndRoleName(tenantId, request.getRoleName())) {
            throw new RuntimeException("角色名称已存在");
        }
        
        // 生成角色ID
        String roleId = UuidGenerator.makeUuid();
        
        // 创建角色
        TeamRole teamRole = new TeamRole();
        teamRole.setRoleId(roleId);
        teamRole.setTenantId(tenantId);
        teamRole.setRoleName(request.getRoleName());
        teamRole.setRoleAlias(request.getRoleAlias());
        teamRole.setDescription(request.getDescription());
        teamRole.setEnterpriseId(enterpriseId);
        teamRole.setIsActive(true);
        
        TeamRole savedRole = teamRoleRepository.save(teamRole);
        
        // 添加权限
        if (request.getPermissions() != null && !request.getPermissions().isEmpty()) {
            for (String permissionCode : request.getPermissions()) {
                addRolePermission(roleId, permissionCode, enterpriseId);
            }
        }
        
        log.info("Team role created: {} in tenant: {}", request.getRoleName(), tenantId);
        return savedRole;
    }
    
    /**
     * 根据角色ID查找角色
     */
    public Optional<TeamRole> findByRoleId(String roleId) {
        return teamRoleRepository.findByRoleId(roleId);
    }
    
    /**
     * 根据租户ID查找角色列表
     */
    public List<TeamRole> getTenantRoles(String tenantId) {
        return teamRoleRepository.findByTenantIdAndIsActiveTrue(tenantId);
    }
    
    /**
     * 添加角色权限
     */
    @Transactional
    public TeamRolePermission addRolePermission(String roleId, String permissionCode, String enterpriseId) {
        TeamRolePermission permission = new TeamRolePermission();
        permission.setRoleId(roleId);
        permission.setPermissionCode(permissionCode);
        permission.setPermissionName(getPermissionName(permissionCode));
        permission.setPermissionDesc(getPermissionDesc(permissionCode));
        permission.setEnterpriseId(enterpriseId);
        permission.setIsActive(true);
        
        return teamRolePermissionRepository.save(permission);
    }
    
    /**
     * 获取角色权限列表
     */
    public List<TeamRolePermission> getRolePermissions(String roleId) {
        return teamRolePermissionRepository.findByRoleIdAndIsActiveTrue(roleId);
    }
    
    /**
     * 删除角色权限
     */
    @Transactional
    public void removeRolePermission(String roleId, String permissionCode) {
        teamRolePermissionRepository.findByRoleIdAndPermissionCode(roleId, permissionCode)
            .forEach(permission -> {
                permission.setIsActive(false);
                teamRolePermissionRepository.save(permission);
            });
    }
    
    /**
     * 删除角色
     */
    @Transactional
    public void deleteTeamRole(String roleId) {
        TeamRole teamRole = teamRoleRepository.findByRoleId(roleId)
            .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        // 删除角色权限
        teamRolePermissionRepository.deleteByRoleId(roleId);
        
        // 删除角色
        teamRoleRepository.delete(teamRole);
        log.info("Team role deleted: {}", teamRole.getRoleName());
    }
    
    /**
     * 更新角色信息
     */
    @Transactional
    public TeamRole updateTeamRole(String roleId, TeamRoleCreateRequest request) {
        TeamRole teamRole = teamRoleRepository.findByRoleId(roleId)
            .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        // 如果角色名发生变化，检查新名称是否已存在
        if (!teamRole.getRoleName().equals(request.getRoleName()) && 
            teamRoleRepository.existsByTenantIdAndRoleName(teamRole.getTenantId(), request.getRoleName())) {
            throw new RuntimeException("角色名称已存在");
        }
        
        teamRole.setRoleName(request.getRoleName());
        teamRole.setRoleAlias(request.getRoleAlias());
        teamRole.setDescription(request.getDescription());
        
        return teamRoleRepository.save(teamRole);
    }
    
    /**
     * 获取权限名称
     */
    private String getPermissionName(String permissionCode) {
        // 这里可以根据权限代码返回对应的权限名称
        // 实际项目中可以从配置文件中读取
        switch (permissionCode) {
            case "APP_CREATE": return "应用创建";
            case "APP_UPDATE": return "应用更新";
            case "APP_DELETE": return "应用删除";
            case "APP_START": return "应用启动";
            case "APP_STOP": return "应用停止";
            case "TEAM_MANAGE": return "团队管理";
            case "USER_MANAGE": return "用户管理";
            default: return permissionCode;
        }
    }
    
    /**
     * 获取权限描述
     */
    private String getPermissionDesc(String permissionCode) {
        // 这里可以根据权限代码返回对应的权限描述
        switch (permissionCode) {
            case "APP_CREATE": return "创建应用的权限";
            case "APP_UPDATE": return "更新应用的权限";
            case "APP_DELETE": return "删除应用的权限";
            case "APP_START": return "启动应用的权限";
            case "APP_STOP": return "停止应用的权限";
            case "TEAM_MANAGE": return "管理团队的权限";
            case "USER_MANAGE": return "管理用户的权限";
            default: return "系统权限";
        }
    }
}





